// Created by Joe on 2017/8/3.

app.controller(
    'HotlineController',
    [
        'KEY', 'config', '$scope', '$location', '$timeout', 'UserService', 'HotlineService',
        function (KEY, config, $scope, $location, $timeout, UserService, HotlineService) {
            init();

            function init() {
                // animate switch
                $.fx.off = config.forbiddenAnimate;

                // set move
                $scope.position = config.Hotline;

                // set page
                $scope.page = ['home', 'detail', 'mask'];
                $scope.panel = {empty: false, load: false, show: false, info: '', height: 0, top: 0};
                $scope.limit = {list: 5, step: 200, height: 600 - config.borderMask};
                $scope.control = {page: 0, list: 0, listIndex: -1, da: '', mask: false, keyboard: false};

                // current position
                $scope.cp = $scope.position[$scope.page[$scope.control.page]];

                // set focus
                // @ci: current id
                $scope.focus = {ci: $scope.cp[0].id};

                // set selector
                $scope.selector = {$content: $('.scroll')};

                // set ele
                $scope.ele = null;

                // set data
                $scope.data = {
                    filter: {number: '', pass: ''},
                    list: [],
                    curList: [],
                    detail: {}
                };

                // set info <-> input map
                $scope.infoMap = {
                    'hotline-mk1': 'number',
                    'hotline-mk2': 'pass'
                };

                // add logic
                addLogic();

                // get info
                $scope.panel.load = true;
                HotlineService.getHistoryInfo()
                    .then(function (info) {
                        info.forEach(function (item) {
                            var contentList = parseContent(item);
                            $scope.data.list.push({
                                title: item.title,
                                number: item.number,
                                pass: item.pass,
                                question: contentList[0],
                                image: item.attachment ? item.attachment.split('|') : [],
                                replay: contentList[1] || {content: '暂无信息', time: ''},
                                more: contentList.slice(2)
                            });
                        });

                        $scope.data.curList = $scope.data.list.slice(
                            $scope.control.list, $scope.control.list + $scope.limit.list
                        );

                        if ($scope.data.list.length > $scope.limit.list)
                            $scope.control.da = 'arrow-down--blur';

                        $scope.panel.load = false;
                        $scope.panel.empty = $scope.data.list.length === 0;
                    });

                // ele action
                $scope.move = function (evt, cb) {
                    evt.preventDefault();
                    switch (evt.keyCode) {
                        case KEY.UP:
                            if ($scope.control.mask) {
                                moveShim('up');
                            } else {
                                if ($scope.control.list === 0 && $scope.control.listIndex === 0) {
                                    $scope.control.listIndex = -1;
                                    $scope.focus.ci = 'hotline-h1';
                                    // force focus
                                    document.getElementById('hotline-h1').focus();
                                } else {
                                    moveShim('up', 'dynamic');
                                }
                            }
                            break;
                        case KEY.DOWN:
                            if ($scope.control.mask) {
                                moveShim('down');
                            } else {
                                if (evt.target.id === 'hotline-h1' && $scope.data.list.length > 0) {
                                    $scope.control.listIndex = 0;
                                } else {
                                    moveShim('down', 'dynamic');
                                }
                            }
                            break;
                        case KEY.LEFT:
                            moveShim('left');
                            break;
                        case KEY.RIGHT:
                            moveShim('right');
                            break;
                        case KEY.ENTER:
                            if (evt.target.id === 'hotline-mk1' || evt.target.id === 'hotline-mk2') {
                                $scope.ele = evt.target;
                                $scope.ele.style.border = '2px solid #46a7e7';
                                $scope.ele.style.opacity = '1';
                                $('.city__hotline-mb').css('top', -35);
                                inputFlag = true;
                                $scope.control.keyboard = true;
                                save_old_index();
                                change_components(0, 0, keyboardArray);
                                $timeout(function () {
                                    $("#keyboard_a").focus();
                                });
                            } else {
                                cb instanceof Function && cb();
                            }
                            break;
                    }
                };

                // global action
                document.addEventListener('keydown', globalAction);
            }

            function addLogic() {
                // open filter
                $scope.openFilter = function () {
                    if ($scope.panel.load) return;
                    $scope.control.mask = true;
                    $scope.panel.empty = false;
                    $scope.cp = $scope.position['mask'];
                    resetFocus();
                };

                // close filter
                $scope.closeFilter = function () {
                    $scope.control.mask = false;
                    $scope.cp = $scope.position['home'];
                    resetFocus();
                };

                // search detail
                $scope.searchDetail = function () {
                    if ($scope.data.filter.number.length === 0) {
                        $scope.panel.info = '查询编号不能为空';
                        return;
                    }

                    if ($scope.data.filter.pass.length === 0) {
                        $scope.panel.info = '查询查询码不能为空';
                        return;
                    }

                    $scope.control.mask = false;
                    pageSwitch(1);

                    $scope.panel.empty = false;
                    $scope.panel.load = true;
                    HotlineService.getAnswerInfo($scope.data.filter.number, $scope.data.filter.pass)
                        .then(function (info) {
                            $scope.panel.load = false;
                            var item = info[0];
                            if (!item) {
                                $scope.panel.empty = true;
                                return;
                            }
                            var contentList = parseContent(item, 'reply');
                            $scope.data.detail = {
                                title: item.titleQ,
                                question: contentList[0],
                                replay: contentList[1] || {content: '暂无信息', time: ''},
                                more: contentList.slice(2)
                            };

                            $timeout(function () {
                                $scope.panel.height = parseInt($scope.selector.$content.css('height'), 10);
                            });
                        });
                };

                // goto detail
                $scope.gotoDetail = function () {
                    pageSwitch(1);

                    $scope.data.detail = $scope.data.curList[$scope.control.listIndex];

                    // mock
                    if (config.mock) {
                        $scope.data.detail.more = [
                            {content: '追问1', time: '2017-08-10 17:12:00'},
                            {content: '回答1', time: '2017-08-10 17:12:00'},
                            {content: '追问2', time: '2017-08-10 17:12:00'},
                            {content: '回答2', time: '2017-08-10 17:12:00'},
                            {content: '追问3', time: '2017-08-10 17:12:00'},
                            {content: '回答3', time: '2017-08-10 17:12:00'},
                            {content: '追问4', time: '2017-08-10 17:12:00'}
                        ]
                    }

                    $timeout(function () {
                        $scope.panel.height = parseInt($scope.selector.$content.css('height'), 10);
                    });
                }
            }

            function parseContent(info, type) {
                var splitFlag = {
                    pump: '',
                    pumpSource: '· 原问题：',
                    pumpReply: '· 12345回复：',
                    pumpMoreAsk: '· 追加提问：',
                    decollator: '\n—————————\n',
                    timeLabel: 'date:'
                };

                var contentList = info.contentQ.split(splitFlag.decollator);

                if (type === 'reply') {
                    contentList.push(info.reply);
                } else if (info.isBack === '1') {
                    contentList.push(info.contentA);
                }

                var resultList = [];
                if (contentList.length > 2) {
                    contentList.forEach(function (item) {
                        item = item.replace(/\n/g, '')
                            .replace(splitFlag.pumpMoreAsk, '')
                            .replace(splitFlag.pumpSource, '')
                            .replace(splitFlag.pumpReply, '');
                        var infoArr = item.split(splitFlag.timeLabel);
                        infoArr[1] = infoArr[1] || '';
                        resultList.push({
                            content: infoArr[0],
                            time: infoArr[1]
                        });
                    });

                    // TODO : need to be confirmed
                    if (true) {
                        resultList[0] = {content: info.contentQ, time: info.createTimeQ};
                        resultList[1] = {content: info.contentA, time: info.createTimeA};
                    }
                } else if (contentList.length === 2) {
                    resultList = [
                        {content: info.contentQ, time: info.createTimeQ},
                        {
                            content: type === 'reply' ? info.reply : info.contentA,
                            time: type === 'reply' ? info.createTime : info.createTimeA
                        }
                    ];
                } else {
                    resultList = [{content: info.contentQ, time: info.createTimeQ}];
                }

                return resultList;
            }

            function resetFocus(pos) {
                pos = pos || 0;
                $scope.focus.ci = $scope.cp[pos]['id'];
            }

            function pageSwitch(page) {
                page = page || 0;
                $scope.control.page = page;
            }

            function moveShim(dir, type) {
                type = type || 'static';
                if (type === 'static') {
                    var curFocus = $scope.cp.filter(function (item) {
                        return item.id === $scope.focus.ci;
                    })[0];
                    if (curFocus['move'][dir] !== -1) {
                        $scope.focus.ci = curFocus['move'][dir];
                    }
                } else {
                    switch (dir) {
                        case 'up':
                            if ($scope.control.da && $scope.control.da !== 'arrow-down--blur') $scope.control.da = 'arrow-down--blur';
                            if ($scope.control.listIndex > 0) {
                                $scope.control.listIndex--;
                            } else {
                                if ($scope.control.list > 0) {
                                    $scope.data.curList = $scope.data.list.slice(
                                        --$scope.control.list, $scope.control.list + $scope.limit.list
                                    );
                                }
                            }
                            break;
                        case 'down':
                            if ($scope.control.listIndex < Math.min($scope.limit.list - 1, $scope.data.list.length - 1)) {
                                $scope.control.listIndex++;
                            } else {
                                if ($scope.control.list + $scope.limit.list < $scope.data.list.length) {
                                    $scope.data.curList = $scope.data.list.slice(
                                        ++$scope.control.list, $scope.control.list + $scope.limit.list
                                    );
                                }
                            }
                            if ($scope.control.list + $scope.limit.list === $scope.data.list.length
                                && $scope.control.listIndex === $scope.limit.list - 1)
                                $scope.control.da = 'arrow-up--blur';
                            break;
                    }
                }
            }

            function globalAction() {
                event.preventDefault();
                var up = function () {
                    if ($scope.control.page === 0) return;

                    if ($scope.panel.top < 0) {
                        $scope.panel.top += $scope.limit.step;
                        // top align
                        $scope.panel.top = $scope.panel.top < 0 ? $scope.panel.top : 0;
                        $scope.selector.$content.stop().animate({top: $scope.panel.top}, {duration: config.animateDelay});
                    }
                };
                var down = function () {
                    if ($scope.control.page === 0) return;

                    // eliminate image loading effect
                    $scope.panel.height = parseInt($scope.selector.$content.css('height'), 10);
                    if ($scope.limit.height - $scope.panel.top < $scope.panel.height) {
                        $scope.panel.top -= $scope.limit.step;
                        // bottom align
                        $scope.panel.top = $scope.limit.height - $scope.panel.top < $scope.panel.height ?
                            $scope.panel.top : $scope.limit.height - $scope.panel.height;
                        $scope.selector.$content.stop().animate({top: $scope.panel.top}, {duration: config.animateDelay});
                    }
                };
                var back = function () {
                    // mask
                    if ($scope.control.mask) return;

                    // detail page
                    if ($scope.control.page === 1) {
                        $scope.data.detail = {};
                        $scope.panel.empty = false;
                        $scope.panel.load = false;
                        $scope.panel.height = 0;
                        $scope.panel.top = 0;
                        $scope.selector.$content.css('top', 0);
                        pageSwitch(0);
                        $scope.cp = $scope.position[$scope.page[$scope.control.page]];
                        resetFocus();
                        return;
                    }

                    // home page
                    if (document.activeElement.id !== 'hotline-h1') {
                        $scope.focus.ci = 'hotline-h1';
                        // force focus
                        document.getElementById('hotline-h1').focus();
                        $scope.control.list = 0;
                        $scope.control.listIndex = -1;
                        $scope.data.curList = $scope.data.list.slice(
                            $scope.control.list, $scope.control.list + $scope.limit.list
                        );

                        if ($scope.data.list.length > $scope.limit.list)
                            $scope.control.da = 'arrow-down--blur';

                        return;
                    }

                    $scope.$apply(function () {
                        $location.path('/home').replace();
                    });
                };
                var enter = function () {
                    if ($scope.control.keyboard) {
                        if (inputFlag) {
                            var curInput = $scope.data.filter[$scope.infoMap[$scope.ele.id]];
                            if (inputLetter) {
                                inputLetter = false;
                                if (/[0-9a-z]/i.test(charContainer)) {
                                    $scope.data.filter[$scope.infoMap[$scope.ele.id]] += charContainer;
                                }
                            }

                            if (document.activeElement.id === 'keyboard_dele') {
                                if ((isChinese && chineseSearch < 0)
                                    || (!isChinese && curInput.length > 0)) {
                                    $scope.data.filter[$scope.infoMap[$scope.ele.id]] = curInput.substr(0, curInput.length - 1);
                                }
                            }
                        } else {
                            $('.city__hotline-mb').css('top', 40);
                            $scope.ele.style.border = '2px solid rgba(255, 255, 255, .1)';
                            $scope.ele.focus();
                            $scope.control.keyboard = false;
                        }
                    }
                };

                switch (event.keyCode) {
                    case KEY.UP:
                        up();
                        break;
                    case KEY.DOWN:
                        down();
                        break;
                    case KEY.BACK:
                        back();
                        break;
                    case KEY.ENTER:
                        enter();
                        break;
                }

                $scope.$digest();
            }

            $scope.$on('$destroy', function () {
                document.removeEventListener('keydown', globalAction);
            });
        }
    ]
);
